<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 警告提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 商品分类选择 -->
      <el-row class="elRow">
        <el-col>
          <span
            >选择商品分类：
            <el-cascader
              v-model="selectedcateKeys"
              :options="cateList"
              :props="cateProps"
              clearable
              @change="handleChange"
            >
            </el-cascader>
          </span>
        </el-col>
      </el-row>

      <!-- tab切换 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数的按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            size="mini"
            @click="addDialogVisiable = true"
            >添加参数</el-button
          >
          <!-- 动态参数的表格 -->
          <el-table :data="manyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 遍历标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="removetag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag tag-input"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editopen(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态参数的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 添加静态参数的按钮 -->
          <el-button
            type="primary"
            :disabled="isBtnDisable"
            size="mini"
            @click="addDialogVisiable = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" style="width: 100%" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 遍历标签 -->
                <el-tag
                  closable
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  @close="removetag(index, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 添加标签 -->
                <el-input
                  class="input-new-tag tag-input"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot:default="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editopen(scope.row.attr_id)"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog
      :title="'添加' + textTitle"
      :visible.sync="addDialogVisiable"
      @close="addDialogClose"
      width="30%"
    >
      <!-- 添加表单 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="subaddParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + textTitle"
      :visible.sync="editDialogVisiable"
      @close="editDialogClose"
      width="30%"
    >
      <!-- 添加表单 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisiable = false">取 消</el-button>
        <el-button type="primary" @click="subeditParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getdata } from "../../network/getdata";
export default {
  name: "params",
  data() {
    return {
      // 商品分裂列表
      cateList: [],
      //被选中的商品分类id
      selectedcateKeys: [],
      //商品分类级联选择
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        checkStrictly: true,
      },
      // tab切换当前活跃
      activeName: "many",
      // 静态表格属性
      onlyTableData: [],
      // 动态参数表格
      manyTableData: [],
      // 添加对话框的显示与隐藏
      addDialogVisiable: false,
      // 添加表单对象
      addForm: {
        attr_name: "",
      },
      //添加表单校验规则
      addFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      //修改对话框的显示与隐藏
      editDialogVisiable: false,
      editForm: {
        attr_id: "",
        attr_name: "",
      },
      editFormRules: {
        attr_name: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
      //是控制添加标签的显示
      inputVisible: false,
      inputValue: "",
    };
  },
  computed: {
    //动态设置添加对话框标题
    textTitle() {
      if (this.activeName === "only") {
        return "静态属性";
      } else {
        return "动态参数";
      }
    },
    //获取分类id
    getCateId() {
      if (this.selectedcateKeys.length === 3) {
        return this.selectedcateKeys[this.selectedcateKeys.length - 1];
      }
      return null;
    },
    // 按钮是否被禁用
    isBtnDisable() {
      //根据选中状态来决定按钮是否禁用
      if (this.selectedcateKeys.length !== 3) {
        return true;
      }
      return false;
    },
  },
  methods: {
    //标签数据的持久化
    saveAtributs(row) {
      //将数据提交到后台持久化
      getdata({
        method: "put",
        url: `categories/${this.getCateId}/attributes/${row.attr_id}`,
        data: {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(","),
        },
      }).then((result) => {
        const res = result.data;
        if (res.meta.status !== 200) {
          //更新失败
          this.$message.error("添加参数失败");
          return;
        }
        //添加成功
        this.$message.success("修改参数项成功");
      });
    },
    //删除标签
    removetag(index, row) {
      //点击删除对应的标签 --- splice 方法返回的是修改后的新数组
      row.attr_vals.splice(index, 1);
      //将修改后的数据提交
      this.saveAtributs(row);
    },
    //标签按钮点击事件
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //标签输入事件
    handleInputConfirm(row) {
      //判断输入的值是否为空
      if (row.inputValue.trim().length === 0) {
        //输入的值为空
        //将当前行的输入的标签置空
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      //将输入的值追加到当前行的 attr_vals中
      row.attr_vals.push(row.inputValue);
      //追加成功之后清空当前行的 inputValue 隐藏输入框
      row.inputValue = "";
      row.inputVisible = false;
      //输入不为空 数据的持久化
      this.saveAtributs(row);
    },
    // 删除参数
    removeParams(attr_id) {
      // console.log(attr_id)
      // 用户删除确认
      this.$confirm("此操作会永久删除该属性,是否继续", "温馨提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //选择确定
          getdata({
            method: "delete",
            url: `/categories/${this.getCateId}/attributes/${attr_id}`,
          }).then((result) => {
            const res = result.data;
            if (res.meta.status !== 200) {
              //删除失败
              this.$message.error("删除失败");
              return;
            }
            //删除成功
            this.$message.success("删除成功");
            //刷新数据
            this.getParamsList();
          });
        })
        .catch(() => {
          //取消操作
          this.$message.info("已取消操作");
        });
    },
    // 提交修改的参数
    subeditParams() {
      //先进行数据校验
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) {
          //数据不合法
          return;
        }

        //数据合法,进行提交
        getdata({
          method: "put",
          url: `categories/${this.getCateId}/attributes/${this.editForm.attr_id}`,
          data: {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          },
        }).then((result) => {
          const res = result.data;
          if (res.meta.status !== 200) {
            //修改失败
            this.$message.error("修改参数失败");
            return;
          }
          //修改数据成功 刷新数据,关闭对话框
          this.$message.success("修改参数成功");
          this.getParamsList();
          this.editDialogVisiable = false;
        });
      });
    },
    // 打开修改对话框
    editopen(attrId) {
      getdata({
        method: "get",
        url: `categories/${this.getCateId}/attributes/${attrId}`,
        params: {
          // 静态还是动态参数
          attr_sel: this.activeName,
        },
      }).then((result) => {
        const res = result.data;
        if (res.meta.status !== 200) {
          //获取失败
          this.$message.error("获取数据失败");
          return;
        }
        // 获取成功
        this.editForm.attr_name = res.data.attr_name;
        this.editForm.attr_id = res.data.attr_id;
        this.editDialogVisiable = true;
      });
    },
    //监听关闭修改对话框事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    // 关闭添加对话框
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加参数
    subaddParams() {
      // 先进行表单的校验
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          //数据不合法
          return;
        }
        //数据合法
        //发起请求
        getdata({
          method: "post",
          url: `categories/${this.getCateId}/attributes`,
          data: {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          },
        }).then((result) => {
          const res = result.data;
          if (res.meta.status !== 201) {
            //添加失败
            this.$message.error("添加失败");
            return;
          }
          //添加成功
          this.$message.success("添加成功");
          // 刷新数据
          this.getParamsList();
          //关闭对话框
          this.addDialogVisiable = false;
        });
      });
    },
    //获取参数列表封装
    getParamsList() {
      //如果选中的不是第三级 -- 清空选中的内容
      if (this.selectedcateKeys.length !== 3) {
        this.selectedcateKeys = [];
        this.manyTableData = [];
        this.onlyTableData = [];
        return;
      }
      //发情请求获取参数列表
      getdata({
        method: "get",
        url: `categories/${this.getCateId}/attributes`,
        params: {
          sel: this.activeName,
        },
      }).then((result) => {
        const res = result.data;
        // console.log(res.data)
        if (res.meta.status !== 200) {
          //获取参数失败
          this.$message.error("获取参数列表失败");
          return;
        }

        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
          // item.attr_vals = ['展示功能','列表']
          //为每一行的添加标签设置初始值和显示
          item.inputVisible = false;
          item.inputValue = "";
        });
        //根据 当前的 tabs 的选中状态来赋值
        if (this.activeName === "only") {
          this.onlyTableData = res.data;
        } else {
          this.manyTableData = res.data;
        }
        console.log(this.manyTableData);
      });
    },
    // 切换监听事件
    handleTabClick() {
      // console.log(this.activeName)
      if (this.selectedcateKeys.length === 3) {
        this.getParamsList();
      }
    },
    // 级联选择框数值改变时的事件
    handleChange() {
      this.getParamsList();
    },
    // 获取商品分类列表
    getCateList() {
      getdata({
        method: "get",
        url: "/categories",
      }).then((result) => {
        const res = result.data;
        if (res.meta.status !== 200) {
          this.$message.err("获取商品分类列表失败");
          return;
        }
        //获取成功
        this.cateList = res.data;
        // console.log(this.cateList)
      });
    },
  },
  created() {
    // 获取分类列表
    this.getCateList();
  },
};
</script>

<style lang="less" scoped>
.elRow {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.tag-input {
  width: 100px;
}
</style>